package com.smartstate.IOC.schedul;//package com.smartstate.EnvironmentMonitor.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.GsonBuilder;
import com.smartstate.IOC.dto.DataDTO;
import com.smartstate.IOC.vo.DataVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@ServerEndpoint(value = "/webSocket/{userId}")
@Component
public class WebSocketCopy {


    private final Logger log = LoggerFactory.getLogger(this.getClass());

    //concurrent包的线程安全Map，用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap<String, WebSocketCopy> webSocketMap = new ConcurrentHashMap<>();

    //存放每个任务的ScheduledFuture对象
    private static ConcurrentHashMap<String, ScheduledFuture> taskMap = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private static Map<String, List<DataVO>> mapData = new HashMap<>();

    private List<DataVO> list = new ArrayList<>();

    private void setSession(Session session) {
        this.session = session;
    }

//    最佳线程数目 = （（线程等待时间+线程CPU时间）/线程CPU时间 ）* CPU数目
    public static ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(500);

    private String userId;

    private DataRealTimeRunnable runnable = new DataRealTimeRunnable();

    private boolean flag = true;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        this.session = session;
        this.userId = userId;
        webSocketMap.put(userId, this);
        sendMessage("连接成功" , userId);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (taskMap.get(userId) != null) {
            taskMap.get(userId).cancel(true);
        }
        webSocketMap.remove(this.userId);
        log.info("有一连接关闭！");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param str 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String str) {
        List<DataVO> list = new ArrayList<>();
        GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        Gson gson = builder.create();
        DataDTO dataDTO = null;
        try {
            dataDTO = gson.fromJson(str, DataDTO.class);
        }catch (Exception e){
            log.info("输入数据格式有误");
            return;
        }
        if (dataDTO == null) {
            return;
        }
        if(dataDTO.getMap().size() == 0)
            return;
        Map<String, List<String>> mapDataDTO = dataDTO.getMap();
        for (String deviceId : mapDataDTO.keySet()) {
            for (String attribute : mapDataDTO.get(deviceId)) {
                DataVO dataVO = new DataVO();
                dataVO.setId(deviceId);
                dataVO.setAttribute(attribute);
                list.add(dataVO);
            }
        }
        runnable.setListAndUserId(list, userId);
        if (flag) {
            ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleWithFixedDelay(runnable, 0,
                    1, TimeUnit.SECONDS);
            taskMap.put(userId, scheduledFuture);
            flag = false;
        }
    }


    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        if (taskMap.get(userId) != null) {
            taskMap.get(userId).cancel(true);
        }
//        WebSocketServerDateTime.ddd.remove(userId);
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Object message, String userId) {
        try {
            webSocketMap.get(userId).session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 实现服务器主动群发消息
     */
    public static void sendInfo(Object message) {
        for (Map.Entry<String, WebSocketCopy> item : webSocketMap.entrySet()) {
            item.getValue().sendMessage(message, item.getKey());
        }
    }

    public static void send(Object message, String userId) {
        try {
            webSocketMap.get(userId).session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

